package com.xjmall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.math.DoubleMath;
import com.xjmall.common.Const;
import com.xjmall.common.ResponseCode;
import com.xjmall.common.ServerResponse;
import com.xjmall.dao.CartMapper;
import com.xjmall.dao.ProductMapper;
import com.xjmall.pojo.Cart;
import com.xjmall.pojo.Product;
import com.xjmall.service.ICartService;
import com.xjmall.util.PropertiesUtil;
import com.xjmall.vo.CartProductVo;
import com.xjmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;

/**
 * Created by An on 2017/5/18.
 */

@Service("/iCartService")
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count) {
        if (productId == null || count == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if (cart == null) {
            // 执行到这，说明该购物车中没有这个商品，需要新增一个商品的记录
            Cart newCart = new Cart();
            newCart.setQuantity(count);
            newCart.setChecked(Const.Cart.CHECKED);
            newCart.setProductId(productId);
            newCart.setUserId(userId);
            cartMapper.insert(newCart);
        } else {
            // 执行到这，说明该购物车中已经包含这个商品，只需要修改数量
            count = cart.getQuantity() + count;
            cart.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        return this.list(userId);
    }

    @Override
    public ServerResponse<CartVo> list(Integer userId) {
        CartVo vo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(vo);
    }

    @Override
    public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count) {
        if (productId == null || count == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if (cart != null) {
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

    @Override
    public ServerResponse<CartVo> deleteProducts(Integer userId, String productIds) {
        List<String> productIdList = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productIdList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdAndProductIds(userId, productIdList);
        return this.list(userId);
    }

    @Override
    public ServerResponse<CartVo> selectOrUnselect(Integer userId, Integer productId, int checked) {
        cartMapper.checkedOrUncheckedProduct(userId, productId, checked);
        return this.list(userId);
    }

    @Override
    public ServerResponse<Integer> getCartProductCount(Integer userId) {
        if (userId == null) {
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
    }

    private CartVo getCartVoLimit(Integer userId) {
        CartVo vo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId); // 该用户的购物车列表
        List<CartProductVo> cartProductVoList = Lists.newArrayList(); // 购物车中的商品信息列表
        String cartTotalPrice = new String("0"); // 购物车总价

        if (CollectionUtils.isNotEmpty(cartList)) {
            for (Cart cartItem : cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if (product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductPrice(new DecimalFormat("0.00").format((product.getPrice()) / 100));
                    cartProductVo.setProductStock(product.getStock());
                    // 判断库存
                    int buyLimitCount = 0;
                    if (product.getStock() >= cartItem.getQuantity()) {
                        // 执行到这，表示库存充足
                        buyLimitCount = cartItem.getQuantity();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    } else {
                        // 执行到这，标识库存不足
                        buyLimitCount = product.getStock();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                        // 修改购物车中的有效库存
                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setId(cartItem.getId());
                        cartForQuantity.setQuantity(buyLimitCount);
                        cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                    }
                    cartProductVo.setQuantity(buyLimitCount);
                    // 计算购物车总价
                    cartProductVo.setProductTotalPrice(new DecimalFormat("0.00").format(Double.valueOf((product.getPrice() * cartProductVo.getQuantity()) / 100)));
                    cartProductVo.setProductChecked(cartItem.getChecked());
                }
                if (cartItem.getChecked() == Const.Cart.CHECKED) {
                    cartTotalPrice = new DecimalFormat("0.00").format(Double.valueOf(cartTotalPrice) + Double.valueOf(cartProductVo.getProductTotalPrice()));
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        vo.setCartProductVoList(cartProductVoList);
        vo.setAllChecked(this.getAllCheckedStatus(userId));
        vo.setCartTotalPrice(cartTotalPrice);
        vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return vo;
    }

    private boolean getAllCheckedStatus(Integer userId) {
        if (userId == null) {
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }
}
